package com.dogkr.server.web;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.dogkr.common.ServerAction;
import com.dogkr.server.entity.Host;
import com.dogkr.server.entity.HostApply;
import com.dogkr.server.entity.User;
import com.dogkr.server.service.HostService;


// 设置Struts2注解
@ParentPackage(value = "login-default")
@Namespace(value = "/host")
@ResultPath("/WEB-INF/jsps")
// 页面文件空间
@Results({
	@Result(name = "Main", location = "main.jsp"),
	@Result(name = "Apply", location = "apply.jsp"),
	@Result(name = "ServerMain", location = "server_main.jsp"),
	
})
public class HostAction extends ServerAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	private HostService hostService;
	
	private Host host;
	
	private HostApply apply;
	
	@Action(value="main")
	public String main() {
		return "Main";
	}
	
	@Action(value="apply")
	public String apply() {
		Host oldHost = hostService.selectByUserKey(this.getLoginUser().getId());
		if(oldHost != null) {
			put("redirectURL", "frame/host.do");
			return "redirect";
		}
		return "Apply";
	}
	
	@Action(value="applySave")
	public void applySave() {
		User user = this.getLoginUser();
		HostApply oldApply = hostService.getApplyByUserId(user.getId());
		if(oldApply == null) {
			apply.create(user);
			hostService.saveApply(apply);
			user.setHostApply(apply);
		} else if(HostApply.STATUS_NEW == oldApply.getStatus()) {
			oldApply.update(apply);
			hostService.saveApply(oldApply);
			user.setHostApply(oldApply);
		}
		outJson(res);
	}
	
	@Action(value="server")
	public String server() {
		return "ServerMain";
	}
	
	@Action(value="get")
	public void get() {
		User user = this.getLoginUser();
		outJson(user.getHost());
	}
	
	@Action(value="getApply")
	public void getApplyByUser() {
		User user = this.getLoginUser();
		HostApply apply = hostService.getApplyByUserId(user.getId());
		outJson(apply);
	}
	
	
	@Action(value="save")
	public void save() {
		User user = this.getLoginUser();
		Host oldHost = user.getHost();
		Host update = new Host();
		update.updateInfo(host);
		update.setId(oldHost.getId());
		hostService.update(update);
		oldHost.updateInfo(update);
		outJson(res);
	}	

	public void setHost(Host host) {
		this.host = host;
	}

	public Host getHost() {
		return host;
	}

	public HostApply getApply() {
		return apply;
	}

	public void setApply(HostApply apply) {
		this.apply = apply;
	}
}
